<script>
export default {
  name: "TestWS",
  data(){
    return {
      ws: null,
    }
  },
  created() {
    this.initWebSocket()
  },
  methods: {
    initWebSocket(){
      // 创建websocket
      this.ws = new WebSocket("ws://api.local_warehouse.test:8989/api/v1/admin");
      // 当socket连接打开时，输入用户名
      this.ws.onopen = this.onopen;
      // 当有消息时根据消息类型显示不同信息
      this.ws.onmessage = this.onmessage;
      this.ws.onclose = function() {
        console.log("连接关闭，定时重连");
      };
      this.ws.onerror = function() {
        console.log("出现错误");
      };
    },
    onopen(e) {
      console.log('连接成功')
      console.log(e)
      this.ws.send('{"type":"ping"}');
    },
    onmessage(e){
      console.log(e)
      console.log(e.data);
      const data = JSON.parse(e.data);
      switch(data['type']){
        // 服务端ping客户端
        case 'ping':
          this.ws.send('{"type":"pong"}');
          break;
      }
    }
  }
}
</script>

<template>
  <div>

  </div>
</template>

<style scoped lang="scss">

</style>
